package com.tsfyun.scm.system.config;

import com.tsfyun.common.base.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**=
     * 写入
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key,Object value){
        try{
            ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
            valueOps.set(key,value);
            return Boolean.TRUE;
        }catch (Exception e){
            logger.error("Redis写入失败 :",e);
        }
        return Boolean.FALSE;
    }

    public boolean set(final String key,Object value,Long expireTime,TimeUnit timeUnit){
        try{
            ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
            valueOps.set(key,value);
            redisTemplate.expire(key, expireTime, timeUnit);
            return Boolean.TRUE;
        }catch (Exception e){
            logger.error("Redis写入失败 :",e);
        }
        return Boolean.FALSE;
    }

    /**=
     * 读取
     * @param key
     * @return
     */
    public Object get(final String key){
        ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
        return valueOps.get(key);
    }

    public String getToString(final String key){
        ValueOperations<String, Object> valueOps = redisTemplate.opsForValue();
        Object val = valueOps.get(key);
        if(StringUtils.isNotEmpty(val)){
            return val.toString();
        }
        return null;
    }


    /**=
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean exists(final String key){
        return redisTemplate.hasKey(key);
    }
    /**=
     * 删除
     * @param key
     * @return
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
}
